package handler

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.uber.org/zap"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"time"
	common "user_service/config"
	"user_service/domain"
	pb "user_service/proto"
	"user_service/utils"
)

type UserServer struct {
	pb.UnimplementedUserServer
	ContextTimeout    time.Duration
	UserRepository    domain.UserRepository    // 添加 userRepo 字段
	CounterRepository domain.CounterRepository // 添加 userRepo 字段
}

func (s *UserServer) GetUserList(ctx context.Context, req *pb.PageInfoRequest) (*pb.UserListResponse, error) {
	// 实现 GetUserList 方法
	return &pb.UserListResponse{}, nil
}

func (s *UserServer) GetUserByMobile(ctx context.Context, mobileRequest *pb.MobileRequest) (*pb.UserInfoResponse, error) {
	zap.S().Infow("Info", "service", common.Configs.Server.ServiceName, "method", "GetUserByMobile", "request", mobileRequest)
	var user domain.User
	user, err := s.UserRepository.GetByMobile(ctx, mobileRequest.Mobile)
	if err != nil {
		return nil, status.Errorf(codes.NotFound, "未查找到该用户")
	}
	userResponse := utils.ModelToResponse(user)
	return userResponse, nil
	//return &pb.UserInfoResponse{}, nil
}

func (s *UserServer) GetUserById(ctx context.Context, req *pb.IdRequest) (*pb.UserInfoResponse, error) {
	// 实现 GetUserById 方法
	user, err := s.UserRepository.GetByID(ctx, req.Id)
	if err != nil {
		return nil, err
	}
	fmt.Println(user)
	return &pb.UserInfoResponse{Password: user.Password, Email: user.Email, Name: user.Name}, nil
}

func (s *UserServer) CreateUser(ctx context.Context, req *pb.CreateUserInfoRequest) (*pb.UserInfoResponse, error) {
	// 密码加密
	user := domain.User{
		ID:       primitive.NewObjectID(),
		Name:     req.Name,
		Email:    req.Email,
		Password: utils.EncryptPassword(req.Password),
		Mobile:   req.Mobile,
	}
	// 添加用户
	userId, _ := s.CounterRepository.NextCounterValue(ctx, domain.CollectionUser)
	user.Id = userId
	err := s.UserRepository.Create(ctx, &user)
	if err != nil {
		return &pb.UserInfoResponse{}, err
	}

	return &pb.UserInfoResponse{
		Id:       user.Id,
		Name:     user.Name,
		Email:    user.Email,
		Password: req.Password,
	}, nil
}

func (s *UserServer) UpdateUser(ctx context.Context, req *pb.UpdateUserInfoRequest) (*pb.UpdateResponse, error) {
	// 实现 UpdateUser 方法
	return &pb.UpdateResponse{}, nil
}

func (s *UserServer) CheckPassword(ctx context.Context, req *pb.CheckPasswordRequest) (*pb.CheckPasswordResponse, error) {
	// 实现 CheckPassword 方法
	//return &pb.CheckPasswordResponse{}, nil
	passResponse := &pb.CheckPasswordResponse{}
	password := req.Password
	EncryptedPassword := req.EncryptedPassword

	fmt.Println(EncryptedPassword, password)
	passResponse.Success = utils.VerifyPassword(EncryptedPassword, password)
	fmt.Println(passResponse)

	return passResponse, nil
}
